#include "setwig.h"
#include "ui_setwig.h"
#include <QUdpSocket>
#include <QHostAddress>
#include <QJsonDocument>
#include <QJsonObject>
#include <QComboBox>

SetWig::SetWig(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::SetWig)
{
    ui->setupUi(this);
    udpSocket = new QUdpSocket(this);
    connect(ui->btnPrimary, &QPushButton::clicked, this, &SetWig::sendBroadcast);
    ui->lineEdit->setEnabled(false);
    connect(ui->listWidget, &QListWidget::itemClicked, this, &SetWig::onItemClicked);
    connect(udpSocket, &QUdpSocket::readyRead, this, &SetWig::readPendingDatagrams);
    connect(ui->connectBtnPrimary, &QPushButton::clicked, this, &SetWig::connectBtnClick);
    connect(ui->comboBox,SIGNAL(currentIndexChanged(int)), this, SLOT(onComboBoxIndexChanged(int)));
    connect(ui->pushButtonRefresh, SIGNAL(clicked()),this, SLOT(refreshBtnClickSlot()));

    QListView* listView = new QListView(this);
    ui->comboBox->setView(listView);

}

SetWig::~SetWig()
{
    delete ui;
}

void SetWig::sendBroadcast()
{
    ui->listWidget->clear();
    // 创建JSON对象
    QJsonObject jsonObject;
    jsonObject["type"] = "device search";
    QJsonDocument jsonDoc(jsonObject);
    QByteArray jsonByteArray = jsonDoc.toJson();
    qDebug() << jsonByteArray;
    udpSocket->writeDatagram(jsonByteArray, QHostAddress(QString("192.168.50.255")), 6667);
}

void SetWig::readPendingDatagrams()
{
    while (udpSocket->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(udpSocket->pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;
        udpSocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
        QJsonDocument jsonDoc = QJsonDocument::fromJson(datagram.data());
        if (!jsonDoc.isNull()) {
            if (jsonDoc.isObject()) {
                QJsonObject jsonObject = jsonDoc.object();
                emit onDatagramRecv(jsonObject);
            }
        } else {
            qDebug() << "Failed to parse JSON";
        }

    }

}

void SetWig::onItemClicked(QListWidgetItem *item)
{
    qDebug() << "Item clicked:" << item->text();
    ui->lineEdit->setText(item->text());
}

void SetWig::connectBtnClick()
{
    if(ui->lineEdit->text() == "")
    {
        QMessageBox::warning(this, "警告", "请输入ip和端口号");
        return;
    }
    QStringList parts = ui->lineEdit->text().split(":");
    if (parts.size() == 2) {
        QString ipAddress = parts.at(0);
        int port = parts.at(1).toInt();

        qDebug() << "IP Address:" << ipAddress;
        qDebug() << "Port:" << port;
        emit connectTcpServer(ipAddress, port);
        //        ui->connectBtnPrimary->setEnabled();
    } else {
        qDebug() << "Invalid address and port format";
    }

}



void SetWig::onComboBoxIndexChanged(int index) {
    QString currentText = ui->comboBox->itemText(index);
    QJsonObject jsonObject;
    jsonObject["type"] = 3;
    QJsonObject data;
    data["type"] = index;

    QJsonDocument jsonDoc(jsonObject);
    QByteArray jsonByteArray;

    if (index == 2) {
        bool ok;
        int value = QInputDialog::getInt(nullptr, "刷新周期", "请输入刷新周期（秒）：", 5, 5, 100, 1, &ok);

        if (ok) {
            data["period"] = value;
            jsonObject["data"] = data;
        } else {
            // 可以选择在这里添加一些错误处理或用户反馈
        }
    } else {
        jsonObject["data"] = data;
    }

    jsonDoc.setObject(jsonObject); // 更新JSON文档对象
    jsonByteArray = jsonDoc.toJson();

    if (GlobalVal::mqtt) { // 检查mqtt指针是否为非空
        QMQTT::Message message;
        message.setTopic("/app/data/down"); // 考虑是否应该使用常量或配置参数
        message.setPayload(jsonByteArray);
        GlobalVal::mqtt->publish(message);
    } else {
        qDebug() << "err";
    }
}

void SetWig::refreshBtnClickSlot()
{
    QJsonObject jsonObject;
    jsonObject["type"] = 1;
    jsonObject["limit"] = "all";
    QJsonDocument jsonDoc(jsonObject);
    QByteArray jsonByteArray = jsonDoc.toJson(QJsonDocument::Indented);
    if (GlobalVal::mqtt) {
        QMQTT::Message message;
        message.setTopic("/app/data/down");
        message.setPayload(jsonByteArray);
        GlobalVal::mqtt->publish(message);
    } else {
        qDebug() << "err";
    }
}

void SetWig::renderListWidgetItem(QString ip, int port)
{
    QListWidgetItem *newItem = new QListWidgetItem(QString("%1:%2").arg(ip).arg(port));
    ui->listWidget->addItem(newItem);
}

void SetWig::setReportMode(int type, int period)
{
    disconnect(ui->comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(onComboBoxIndexChanged(int)));
    ui->comboBox->setCurrentIndex(type);
    connect(ui->comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(onComboBoxIndexChanged(int)));


}
